package com.hmall.gateway.filter;
import cn.hutool.core.text.AntPathMatcher;
import com.hmall.gateway.config.AuthProperties;
import com.hmall.gateway.config.JwtProperties;
import com.hmall.gateway.util.JwtTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.nio.charset.StandardCharsets;
@EnableConfigurationProperties({JwtProperties.class,AuthProperties.class})
@Component
public class AuthGlobalFilter implements GlobalFilter {

    @Autowired
    private AuthProperties authProperties;

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Autowired
    private JwtTool jwtTool;

    /****
     * 用户登录身份拦截校验
     * @param exchange the current server exchange
     * @param chain provides a way to delegate to the next filter
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //0、获取Request和Response对象：获取用户传入的数据 Request，拦截需要用到Response
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //1、校验访问地址是否是开放的地址，如果是，直接放行：   有一些地址是开放的  比如 登录
        String uri = request.getPath().toString();
        if(isExclude(uri)){
            return chain.filter(exchange);
        }

        //2、获取请求头令牌
        String token = request.getHeaders().getFirst("authorization");

        //3、校验令牌是否有效，无效直接拦截
        Long userId = null;
        try {
            userId = jwtTool.parseToken(token);
        } catch (Exception e) {
            //提示参数错误
            response.setStatusCode(HttpStatus.UNAUTHORIZED);// 响应状态码
            response.getHeaders().setContentType(MediaType.APPLICATION_JSON);// 响应JSON类型
            return response.writeWith(Mono.just(response.bufferFactory().wrap("{\"msg\":\"请先登录！\"}".getBytes(StandardCharsets.UTF_8))));
        }

        //4、有效，获取用户ID，并封装到请求头，可以传递给下游服务
        String userInfo = userId.toString();
        exchange.mutate().request(builder -> builder.header("user-info",userInfo));
        //5、放行
        return chain.filter(exchange);
    }

    /***
     * 匹配指定地址是否需要进行拦截
     * @param uri
     * @return  true 不拦截   false  拦截
     */
    public boolean isExclude(String uri){
        return authProperties.getExcludePaths()
                .stream().anyMatch(ep -> antPathMatcher.match(ep, uri));
    }
}